package com.animee.jiujiangdict.collect_frag;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import com.animee.jiujiangdict.ChengyuInfoActivity;
import com.animee.jiujiangdict.R;
import com.animee.jiujiangdict.WordInfoActivity;
import com.animee.jiujiangdict.db.DBManager;
import java.util.ArrayList;
import java.util.List;
/**
 * 收藏界面，收藏文字和成语的碎片
 */
public class ZiFragment extends Fragment {

    GridView gv;
    private String type;
    List<String>mDatas;  //GridView的数据源
    private ArrayAdapter<String> adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_zi, container, false);
        gv = view.findViewById(R.id.zifrag_gv);
        mDatas = new ArrayList<>();
        adapter = new ArrayAdapter<>(getContext(), R.layout.item_search_pgv, R.id.item_sgv_tv, mDatas);
        gv.setAdapter(adapter);
        Bundle bundle = getArguments();
        type = bundle.getString("type");   //获取当前Fragment显示的数据类型
        setGvListener();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        loadData();
    }

    /* 设置GridView的监听事件*/
    private void setGvListener() {
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (type.equals("汉字")) {   //获取汉字列表
                    String zi = mDatas.get(position);
                    Intent intent = new Intent(getActivity(), WordInfoActivity.class);
                    intent.putExtra("zi",zi);
                    startActivity(intent);
                }else{
                    String cyu = mDatas.get(position);
                    Intent intent = new Intent(getActivity(), ChengyuInfoActivity.class);
                    intent.putExtra("chengyu",cyu);
                    startActivity(intent);
                }
            }
        });
    }

    /* 根据类型加载不同数据库当中的数据*/
    private void loadData() {
        List<String> list;
        mDatas.clear();
        if (type.equals("汉字")) {   //获取汉字列表
            list = DBManager.queryAllZiInCollwordtb();  //查询收藏汉字列表当中所有内容

        }else {  //获取收藏成语列表
            list = DBManager.queryAllCyuInCollcyutb();
        }
        mDatas.addAll(list);
        adapter.notifyDataSetChanged();
    }
}
